﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using Runda.CMS.Bll;
using Runda.CMS.Common.Entity;
using Runda.CMS.Common.Utility;
using System.Collections.Generic;
using Telerik.Web.UI;
using System.Text;

namespace Runda.CMS.Portal.SalesManage
{
    public partial class BillAgency : BasePage
    {
        public string SortString
        {
            get
            {
                if (ViewState["SortString"] == null)
                {
                    ViewState["SortString"] = "customername";
                }

                return ViewState["SortString"].ToString();
            }
            set { ViewState["SortString"] = value; }
        }

        

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {

                DataTable dt = new BudgetBll().Companylist(base.CurrentUserID.ToString());
                ddlCompany.DataSource = dt;
                ddlCompany.DataTextField = "Departmentname";
                ddlCompany.DataValueField = "Departmentname";
                ddlCompany.DataBind();
                ddlCompany.Items.Add(new ListItem("--不限--", ""));
                ddlCompany.SelectedValue = "";

                dt = new BudgetBll().Companylist(base.CurrentUserID.ToString());
                ddlBudgetUnit.DataSource = dt;
                ddlBudgetUnit.DataTextField = "Departmentname";
                ddlBudgetUnit.DataValueField = "Departmentname";
                ddlBudgetUnit.DataBind();
                ddlBudgetUnit.Items.Add(new ListItem("--未知--", ""));
                ddlBudgetUnit.SelectedValue = "";

                dt = new BudgetBll().Companylist(base.CurrentUserID.ToString());
                ddlCompany1.DataSource = dt;
                ddlCompany1.DataTextField = "Departmentname";
                ddlCompany1.DataValueField = "Departmentname";
                ddlCompany1.DataBind();
                ddlCompany1.Items.Add(new ListItem("--不限--", ""));
                ddlCompany1.SelectedValue = "";

                LoadRadTree("");
                BindGrid(1);

                if (ddlCompany.SelectedValue != "")
                {
                    Adjustbillstatus(ddlCompany.SelectedValue, ddlBudgetYear.SelectedValue, ddlBudgetMonth.SelectedValue);
                }
                

            }
        }
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            BindGrid(AspNetPager1.CurrentPageIndex);
            //Calculate();
        }

        protected void btnRefershBillInfo_Click(object sender, EventArgs e)
        {
            
        }

        protected void btnSaveSubItems_Click(object sender, EventArgs e)
        {
            BudgetBll bll = new BudgetBll();
            List<BGSalesBillsEntity> items = new List<BGSalesBillsEntity>();

            foreach (Telerik.WebControls.GridItem item in gridAccessoryList.Items)
            {
                if (item.ItemType == Telerik.WebControls.GridItemType.Item || item.ItemType == Telerik.WebControls.GridItemType.AlternatingItem)
                {
                    Guid ItemID = new Guid(item.OwnerTableView.DataKeyValues[item.ItemIndex]["billGUID"].ToString());
                    CheckBox chkSel = item.FindControl("chkSel") as CheckBox;
                    if (chkSel.Checked)
                    {
                        BGSalesBillsEntity sub = bll.Get<BGSalesBillsEntity>(ItemID);
                        sub.BudgetUnit = ddlBudgetUnit.SelectedValue;
                        sub.UpdatedOn = System.DateTime.Now;
                        sub.Updatedby = base.CurrentUserID;
                        items.Add(sub);
                    }
                }
            }

            bll.UpdateSalesBills(items);

            ClientScript.RegisterStartupScript(this.GetType(), "保存提示！", "alert('调整成功！');", true);
            BindGrid(AspNetPager1.CurrentPageIndex);
        }

        protected void gridAccessoryList_ItemCommand(object source, Telerik.WebControls.GridCommandEventArgs e)
        {
            if (e.CommandName.ToLower() == "delete")
            {

                BudgetBll bll = new BudgetBll();

                bll.DeleteBGSalesBill(new Guid(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["billGUID"].ToString()));

            }
            BindGrid(AspNetPager1.CurrentPageIndex);
            //Calculate();
        }

        protected void gridAccessoryList_ItemDataBound(object sender, Telerik.WebControls.GridItemEventArgs e)
        {
            if (e.Item.ItemType == Telerik.WebControls.GridItemType.Item || e.Item.ItemType == Telerik.WebControls.GridItemType.AlternatingItem)
            {
                LinkButton lnkbtnDelete = e.Item.FindControl("lnkbtnDelete") as LinkButton;
                if (lnkbtnDelete != null)
                {
                    //DataRowView dv = e.Item.DataItem as DataRowView;
                    //if (new BudgetBll().GetBudgetSubmitStatus(ddlBudgetYear.SelectedValue.ToString(), dv["ProductManager"].ToString()) > 0 || !base.CheckUserHasFuction(1, "Func10011"))
                    //{ lnkbtnDelete.Visible = false; }

                    //lnkEdit.NavigateUrl = "~/Budget/SalesbudgetDetail.aspx?AssistID=" + dv["AssistID"].ToString();
                    lnkbtnDelete.OnClientClick = "return OnDelConfirm();";
                }
            }
        }

        protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        {
            BindGrid(AspNetPager1.CurrentPageIndex);
            //Calculate();
        }

        protected void btnRefersh_Click(object sender, EventArgs e)
        {
            BindGrid(AspNetPager1.CurrentPageIndex);
            //Calculate();
        } 

        private void BindGrid(int pageindex)
        {
            string sb = getWhereClause();

            int RecordCount = 0;
            DataTable dt = new BillBll().GetSalesBills(sb, SortString, AspNetPager1.PageSize, pageindex, out RecordCount);

            AspNetPager1.RecordCount = RecordCount;
            gridAccessoryList.DataSource = dt;
            gridAccessoryList.DataBind();
        }

        private void Calculate()
        {
            string sb = getWhereClause();

            BudgetBll bll = new BudgetBll();
            DataTable dt = bll.CalcSalesBudgets(sb);

            if (dt != null && dt.Rows.Count > 0)
            {
                //hfsumQ1quantity.Value = string.Format("{0:N}", dt.Rows[0]["sumQ1quantity"]);
                //hfsumQ1Amount.Value = string.Format("{0:N}", dt.Rows[0]["sumQ1Amount"]);
                //hfsumQ1Cost.Value = string.Format("{0:N}", dt.Rows[0]["sumQ1Cost"]);
                //hfsumQ1RentAmount.Value = string.Format("{0:N}", dt.Rows[0]["sumQ1RentAmount"]);

                //hfsumQ2quantity.Value = string.Format("{0:N}", dt.Rows[0]["sumQ2quantity"]);
                //hfsumQ2Amount.Value = string.Format("{0:N}", dt.Rows[0]["sumQ2Amount"]);
                //hfsumQ2Cost.Value = string.Format("{0:N}", dt.Rows[0]["sumQ2Cost"]);
                //hfsumQ2RentAmount.Value = string.Format("{0:N}", dt.Rows[0]["sumQ2RentAmount"]);

                //hfsumQ3quantity.Value = string.Format("{0:N}", dt.Rows[0]["sumQ3quantity"]);
                //hfsumQ3Amount.Value = string.Format("{0:N}", dt.Rows[0]["sumQ3Amount"]);
                //hfsumQ3Cost.Value = string.Format("{0:N}", dt.Rows[0]["sumQ3Cost"]);
                //hfsumQ3RentAmount.Value = string.Format("{0:N}", dt.Rows[0]["sumQ3RentAmount"]);

                //hfsumQ4quantity.Value = string.Format("{0:N}", dt.Rows[0]["sumQ4quantity"]);
                //hfsumQ4Amount.Value = string.Format("{0:N}", dt.Rows[0]["sumQ4Amount"]);
                //hfsumQ4Cost.Value = string.Format("{0:N}", dt.Rows[0]["sumQ4Cost"]);
                //hfsumQ4RentAmount.Value = string.Format("{0:N}", dt.Rows[0]["sumQ4RentAmount"]);
                //hfsumTotalAmount.Value = string.Format("{0:N}", dt.Rows[0]["TotalAmount"]);
                //hfsumTotalRentAmount.Value = string.Format("{0:N}", dt.Rows[0]["TotalRentAmount"]);

            }
            else
            {
                //hfsumQ1quantity.Value = "0";
                //hfsumQ1Amount.Value = "0";
                //hfsumQ1Cost.Value = "0";
                //hfsumQ1RentAmount.Value = "0";

                //hfsumQ2quantity.Value = "0";
                //hfsumQ2Amount.Value = "0";
                //hfsumQ2Cost.Value = "0";
                //hfsumQ2RentAmount.Value = "0";

                //hfsumQ3quantity.Value = "0";
                //hfsumQ3Amount.Value = "0";
                //hfsumQ3Cost.Value = "0";
                //hfsumQ3RentAmount.Value = "0";

                //hfsumQ4quantity.Value = "0";
                //hfsumQ4Amount.Value = "0";
                //hfsumQ4Cost.Value = "0";
                //hfsumQ4RentAmount.Value = "0";
                //hfsumTotalAmount.Value = "0";

            }
        }

        protected void gridAccessoryList_SortCommand(object source, Telerik.WebControls.GridSortCommandEventArgs e)
        {
            string OrderBy = e.SortExpression + " " + (e.NewSortOrder == Telerik.WebControls.GridSortOrder.Ascending ? "asc" : "desc");
            SortString = OrderBy;
            BindGrid(1);
            //Calculate();
            

        }

        private string getWhereClause()
        { 
            StringBuilder sb = new StringBuilder();

            sb.Append(" and SourceType in(1,2)");
            if (ddlBudgetYear.SelectedValue != string.Empty)
            {
                sb.Append(" and datepart(year,a.[dDate])  = ").Append(ddlBudgetYear.SelectedValue).Append("");
            }

            if (ddlBudgetMonth.SelectedValue != string.Empty)
            {
                sb.Append(" and datepart(month,a.[dDate])  = ").Append(ddlBudgetMonth.SelectedValue).Append("");
            }

            if (this.txtCustomerName.Text.Trim() != "")
            {
                sb.Append(" and c.[CustomerName]  like '%").Append(txtCustomerName.Text.Trim()).Append("%'");
            }

            string categoryCode = "";

            SystemBll bll = new SystemBll();

            if (Text1.Value != "")
            {
                Guid ID = new Guid(Text1.Value);
                CtrtInstrumentCategoryEntity instrmentEntity = bll.Get<CtrtInstrumentCategoryEntity>(ID);
                if (instrmentEntity != null)
                {
                    categoryCode = instrmentEntity.categoryCode;
                }
                sb.Append(" and a.[cCategorycode]  like '").Append(categoryCode).Append("%'");
            }

            //int RecordCount = 0;
            //RecordCount = new BudgetBll().getDataright(base.CurrentUserID.ToString());

            //if (RecordCount == 0)
            //{ sb.Append(" and ([productmanager] ='").Append(base.CurrentUserEntity.UserName).Append("'").Append(" or [biller] ='").Append(base.CurrentUserID.ToString()).Append("')"); }
            //else
            //{ sb.Append(" and [productmanager] in(").Append("select username from vw_sysUser where DepartmentID in(select DepartmentID from Cms_Sys_UserDepartment_DataRight where userid ='").Append(base.CurrentUserID.ToString()).Append("'))"); }

            if (ddlAdjust.SelectedValue == "1")
            {
                sb.Append(" and BillUnit=BudgetUnit");
            }
            else if (ddlAdjust.SelectedValue == "2")
            { sb.Append(" and BillUnit!=BudgetUnit"); }
            if (ddlCompany.SelectedValue != "")
            {
                sb.Append(" and BillUnit='").Append(ddlCompany.SelectedValue.ToString()).Append("'");
            }
            if (ddlCompany1.SelectedValue != "")
            {
                sb.Append(" and BudgetUnit='").Append(ddlCompany1.SelectedValue.ToString()).Append("'");
            }
            
            if (txtCustomerName.Text.Trim() != "")
            {
                sb.Append(" and customerID in(").Append("select customerid from cms_ctrt_customer where customername like '%").Append(txtCustomerName.Text.Trim()).Append("%')");
            }
            
            

            return sb.ToString();
        }

        protected void btnExportExcel_Click(object sender, EventArgs e)
        {
            string Whereclause = getWhereClause();

            BillBll bll = new BillBll();

            DataTable dt = bll.ExportSaleBills(Whereclause);

            Export.Export2Excel(dt, "销售发票明细", Page.Response);

        }

        protected void lnkbtnSubmit_Click(object sender, EventArgs e)
        {

            BudgetBll bll = new BudgetBll();
            bll.SubmmitBudget(ddlBudgetYear.SelectedValue.ToString(), base.CurrentUserEntity.UserName);
            

        }

        protected void lnkbtnCheck_Click(object sender, EventArgs e)
        {

            BudgetBll bll = new BudgetBll();
            //bll.CheckBudget(ddlBudgetYear.SelectedValue.ToString(), base.CurrentUserEntity.UserName);
        }

        private void LoadRadTree(string categoryCode)
        {
            string categoryGUID = "";
            //List<CtrtInstrumentCategoryEntity> categoryEntitys = new CtrtInstrumentCategoryBll().GetAll<CtrtInstrumentCategoryEntity>(" and parentGUID is null", "Order By categoryCode"); 
            DataTable dt = null;
            CtrtInstrumentCategoryBll bll = new CtrtInstrumentCategoryBll();
            dt = bll.GetInstrumentCategory("");//  and SUBSTRING(categorycode,1,2) in('01', '02')


            RadTreeView RadTreeProdType = RadComboBox_ProdType.Items[0].FindControl("RadTreeView_ProdType") as RadTreeView;
            //HtmlInputHidden Hidden_ProdTypeID = Page.FindControl("Text1") as HtmlInputHidden;
            //HtmlInputText txtSelectType = Page.FindControl("txt_SelectType") as HtmlInputText;
            if (RadTreeProdType != null)
            {
                RadTreeProdType.DataFieldID = "categoryGUID";
                RadTreeProdType.DataTextField = "categoryName";
                RadTreeProdType.DataValueField = "categoryGUID";
                RadTreeProdType.DataFieldParentID = "parentGUID";
                RadTreeProdType.DataSource = dt;
                RadTreeProdType.DataBind();
            }
            if (categoryCode != "")
            {
                Text1.Value = categoryCode;
                List<CtrtInstrumentCategoryEntity> categoryEntitys = new CtrtInstrumentCategoryBll().GetAll<CtrtInstrumentCategoryEntity>(" and parentGUID is null", "Order By categoryCode");

                if (categoryEntitys != null && categoryEntitys.Count > 0)
                {
                    categoryGUID = categoryEntitys[0].categoryCode;
                }

                if (categoryGUID != "")
                {
                    txt_SelectType.Value = RadTreeProdType.FindNodeByValue(categoryGUID).Text;

                    RadComboBox_ProdType.SelectedItem.Value = RadTreeProdType.FindNodeByValue(categoryGUID).Text;
                    RadComboBox_ProdType.SelectedItem.Text = RadTreeProdType.FindNodeByValue(categoryGUID).Text;
                    RadComboBox_ProdType.Text = RadTreeProdType.FindNodeByValue(categoryGUID).Text;
                }
            }

        }

        protected void chkSelAll_CheckedChanged(object sender, EventArgs e)
        {
            foreach (Telerik.WebControls.GridItem item in gridAccessoryList.Items)
            {
                if (item.ItemType == Telerik.WebControls.GridItemType.Item || item.ItemType == Telerik.WebControls.GridItemType.AlternatingItem)
                {
                    CheckBox chkSel = item.FindControl("chkSel") as CheckBox;
                    chkSel.Checked = chkSelAll.Checked;
                }
            }

        }

        private void Adjustbillstatus(string company, string sYear, string sMonth)
        {
            BudgetBll bll = new BudgetBll();
            if (bll.AccountCloseStatus(sYear, sMonth, company) == 1)
            {
                msg.Text = "已关账！";
                hidMsg.Value = "1";
                Button4.Enabled = false;
                btnSaveSubItems.Visible = false;
                ddlBudgetUnit.Enabled = false;
            }
            else
            {
                msg.Text = "";
                hidMsg.Value = "0";
                Button4.Enabled = true;
                btnSaveSubItems.Visible = true;
                ddlBudgetUnit.Enabled = true;
            }
        }

        protected void ddlCompany_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlCompany.SelectedValue != "")
            {
                BudgetBll bll = new BudgetBll();
                string UnlockYearmonth = bll.GetunCloseMonth(ddlCompany.SelectedValue);
                ddlBudgetMonth.SelectedValue = UnlockYearmonth.Substring(5, 2);
                
                Adjustbillstatus(ddlCompany.SelectedValue, ddlBudgetYear.SelectedValue, ddlBudgetMonth.SelectedValue);
            }

        }

        protected void ddlBudgetMonth_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlCompany.SelectedValue != "")
            {
                Adjustbillstatus(ddlCompany.SelectedValue, ddlBudgetYear.SelectedValue, ddlBudgetMonth.SelectedValue);
            }
        }

        protected void ddlBudgetYear_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlCompany.SelectedValue != "")
            {
                Adjustbillstatus(ddlCompany.SelectedValue, ddlBudgetYear.SelectedValue, ddlBudgetMonth.SelectedValue);
            }
        }

       

        protected void Button4_Click(object sender, EventArgs e)
        {

            BudgetBll bll = new BudgetBll();
            string company, sYear, sMonth;
            company = ddlCompany.SelectedValue.ToString();
            sYear = ddlBudgetYear.SelectedValue.ToString();
            sMonth = ddlBudgetMonth.SelectedValue.ToString();

            if (company == "")
            {
                msg.Text = "请选择开票公司。";
                return;
            }

            if (bll.AccountCloseStatus(sYear, sMonth, company) == 1)
            {
                msg.Text = "选择月份的代开票调整已关毕";
                return;
            }

            bll.setDataCloseStatus(sYear, sMonth, company, "1", base.CurrentUserEntity.UserName, DateTime.Now);
            msg.Text = "成功关闭代开票调整。";
        }


    }
}
